package com.cocotingo.snail.dispatcher;

import java.awt.EventQueue;
import java.lang.reflect.InvocationTargetException;

public final class Dispatcher {
	
	private Dispatcher() {
	}
	
	private static final ReusableThreadPool POOL = new ReusableThreadPool();
	
	public static void execute(Runnable target) {
		POOL.execute(target);
	}
	
	public static void executeAndWait(final Runnable target) {
		final Blocker blocker = new Blocker();
		POOL.execute(new Runnable() {
			@Override
			public void run() {
				target.run();
				blocker.unlock();
			}
		});
		try {
			blocker.lock();
		} catch (InterruptedException e) {
			throw new IllegalStateException("current thread was interrupted.", e);
		}
	}
	
	public static void executeAndSyncWithGUI(Runnable target) {
		EventQueue.invokeLater(target);
	}
	
	public static void executeAndWaitAndSyncWithGUI(Runnable target) {
		try {
			EventQueue.invokeAndWait(target);
		} catch (InterruptedException e) {
			throw new IllegalStateException("current thread was interrupted.", e);
		} catch (InvocationTargetException e) {
			throw new IllegalStateException("Dispatcher crashed.", e);
		}
	}
	
	public static void drainThreadPool() {
		POOL.drain();
	}

}
